package com.softcomputer.rpt.web;

import com.softcomputer.rpt.ejb.ExCourseSession;
import com.softcomputer.rpt.ejb.UserSession;
import com.softcomputer.rpt.entity.ExCourse;
import com.softcomputer.rpt.entity.LogMessage;
import java.math.BigDecimal;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "manage")
@SessionScoped
public class OperationManagementBean {

    @EJB
    private ExCourseSession exCourseSession;
    @EJB
    private UserSession userSession;
    private LogMessage logMessage;
    private ExCourse course;
    private List<BigDecimal> values;
    private List<String> currencies;
    private String sellCurrency;
    private String buyCurrency;

    public OperationManagementBean() {
    }

    public LogMessage getMessage() {
        if (logMessage == null) {
            logMessage = new LogMessage();
        }
        return logMessage;
    }

    public List<LogMessage> getMessages() {
        return userSession.retrieve();
    }

    public void setMessage(String text) {
        logMessage.setMessage(text);
    }

    public void saveMessage() {

        BigDecimal relativeCourse = exCourseSession.getExchangeRate(sellCurrency, buyCurrency);

        BigDecimal purchased = new BigDecimal(logMessage.getMessage()).multiply(relativeCourse);

        StringBuilder s = new StringBuilder();

        s.append("sold: ");
        s.append(logMessage.getMessage());
        s.append(sellCurrency);
        s.append(", purchased: ");
        s.append(purchased);
        s.append(buyCurrency);

        logMessage.setMessage(s.toString());
        userSession.persist(logMessage);

        sellCurrency = null;
        buyCurrency = null;
        logMessage = null;
    }

    public void setId(long id) {
        logMessage.setId(id);
    }

    public List<BigDecimal> getValues() {
        values = exCourseSession.getValues();
        return values;
    }

    public ExCourse getCourse() {
        if (course == null) {
            course = new ExCourse();
        }
        return course;
    }

    public List<ExCourse> getExchangeCourses() {
        return exCourseSession.retrieve();
    }

    public List<String> getCurrencies() {
        currencies = exCourseSession.getCurrency();
        return currencies;
    }

    public String getSellCurrency() {
        return sellCurrency;
    }

    public void setSellCurrency(String curr) {
        sellCurrency = curr;
    }

    public String getBuyCurrency() {
        return buyCurrency;
    }

    public void setBuyCurrency(String curr) {
        buyCurrency = curr;
    }
}
